package com.UnionPayCenter.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
	
	/**
	 * 获取openid的接口地址
	 */
	public static final String WX_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=JSCODE&grant_type=authorization_code";
	
	/**
	 * 获取access_token的接口地址
	 */
	public static final String WX_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 
	
	/**
	 * 获取ticket的接口地址
	 */
	public static final String WX_TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card";

	
	/**
	 * HTTP Get 请求
	 * @param urlStr
	 * @return
	 * @throws Exception 
	 */
	public static String httpGetRequest(String urlStr) throws Exception {
		String result = null;
		try {
			//建立http连接
			URL url = new URL(urlStr);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setConnectTimeout(5000);
	        urlConnection.setReadTimeout(5000);
	        urlConnection.setRequestMethod("GET");
	        urlConnection.connect();
	        //获取返回值
	        if (urlConnection.getResponseCode() == 200) {
				InputStream inputStream = urlConnection.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
				String line;
				StringBuffer buffer = new StringBuffer();
				while ((line=reader.readLine())!=null) {
				    buffer.append(line);
				}
				
				result = buffer.toString();
				urlConnection.disconnect();
				reader.close();
			} else {
				throw new Exception();
			}
		} catch (Exception e) {
			throw e; 
		}
		
		return result; 
	}
}
